package library

import (
	"context"
	"encoding/json"

	"go-mall/common/logger"
	"go-mall/common/util/httptool"
)

type WhoisLib struct {
	ctx context.Context
}

func NewWhoisLib(ctx context.Context) *WhoisLib {
	return &WhoisLib{ctx: ctx}
}

// 将下列字段生成结构体定义 ，名称为WhoisIpDetail
// "ip": "8.8.4.4",
// "success": true,
// "type": "IPv4",
// "continent": "North America",
// "continent_code": "NA",
// "country": "United States",
// "country_code": "US",
// "region": "California",
// "region_code": "CA",
// "city": "Mountain View",
// "latitude": 37.3860517,
// "longitude": -122.0838511,
// "is_eu": false,
// "postal": "94039",
// "calling_code": "1",
// "capital": "Washington D.C.",
// "borders": "CA,MX",
type WhoisIpDetail struct {
	Ip            string  `json:"ip"`
	Success       bool    `json:"success"`
	Type          string  `json:"type"`
	Continent     string  `json:"continent"`
	ContinentCode string  `json:"continent_code"`
	Country       string  `json:"country"`
	CountryCode   string  `json:"country_code"`
	Region        string  `json:"region"`
	RegionCode    string  `json:"region_code"`
	City          string  `json:"city"`
	Latitude      float64 `json:"latitude"`
	Longitude     float64 `json:"longitude"`
	IsEu          bool    `json:"is_eu"`
	Postal        string  `json:"postal"`
	CallingCode   string  `json:"calling_code"`
	Capital       string  `json:"capital"`
	Borders       string  `json:"borders"`
}

func (whois *WhoisLib) GetHostIpDetail() (*WhoisIpDetail, error) {
	log := logger.New(whois.ctx)
	httpStatusCode, respBody, err := httptool.Get(whois.ctx,
		"https://ipwho.is",
		httptool.WithHeader(map[string]string{
			"User-Agent": "curl/7.64.1",
		}))
	if err != nil {
		log.Error("whois request error",
			"err", err,
			"httpStatusCode", httpStatusCode)
		return nil, err
	}
	reply := new(WhoisIpDetail)
	json.Unmarshal(respBody, reply)
	return reply, nil
}
